package com.qidian.server.socket;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.qidian.common.Constants;


public class FileServer extends Thread{

	protected String	serverIP	;
    protected int		serverPort	;
    protected int 		num_threads = Constants.num_threads_send_file ;
    protected ServerSocket serverSocket = null;
    protected boolean      isStopped    = false;
    protected Thread       runningThread= null;
    protected ExecutorService threadPool = Executors.newFixedThreadPool(num_threads);
   
    
//    public FileServer(){
//    } 
    public FileServer(String ip ,int port){
    	this.serverIP = ip ;
        this.serverPort = port;
    }

    public int getPort()
    {
    	return serverPort ;
    }
    
    public void run(){
        synchronized(this){
            this.runningThread = Thread.currentThread();
        }
        openServerSocket();
        while(! isStopped()){
            Socket clientSocket = null;
            try {
                clientSocket = this.serverSocket.accept();
            } catch (IOException e) {
                if(isStopped()) {
                    System.out.println("Server Stopped.") ;
                    return;
                }
                throw new RuntimeException(
                    "Error accepting client connection", e);
            }
            this.threadPool.execute(new FileWorker(clientSocket,"Thread Pooled Server"));
        }
        this.threadPool.shutdown();
        System.out.println("Server Stopped.") ;
    }


    private synchronized boolean isStopped() {
        return this.isStopped;
    }

    public synchronized void stopServer(){
        this.isStopped = true;
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }
    }

    private void openServerSocket() {
        try 
        {
        	System.out.println("FileServer start up "+this.serverIP+":"+this.serverPort);
        	InetSocketAddress endpoint = new InetSocketAddress(this.serverIP,serverPort);
        	serverSocket = new ServerSocket();
            serverSocket.setPerformancePreferences(1, 1, 0) ;
            serverSocket.bind(endpoint) ;
        } catch (IOException e) {
            throw new RuntimeException("Cannot open port "+this.serverPort, e);
        }
    }
    
    
    public static void main(String[] args) throws InterruptedException
    {
    	FileServer server = new FileServer("127.0.0.1",54332) ;
//    	server.run() ;
    	server.start() ;
    	System.out.println(123);
    	Thread.sleep(30*1000);
    	System.out.println(456);
    	server.stopServer() ;
    	System.out.println(789);
    	return ;
    }
}